package com.memoryangelapplication.notification;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.memoryangelapplication.MemoryAngelListViewUserAdapter;
import com.memoryangelapplication.MemoryAngelUserRegister;
import com.memoryangelapplication.R;
import com.memoryangelapplication.constant.MemoryAngelConstant;
import com.memoryangelapplication.services.GMailSender;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;

public class MemoryAngel_Subscription extends Activity {
    String sendingEmail = "";
    String Name = "" , PhoneNo = "0";
    JSONObject jsonobject;
    JSONArray jsonarray;
    InputStream is = null;
    StringBuilder sb = null;
    int timeoutConnection = 5000;
    HttpParams httpParameters = new BasicHttpParams();
    String result;
    String mainUrl = null;
    JSONArray jArray;
    String messageCarer,CareerName, CareerSMS;
    ArrayList<HashMap<String, String>> arraylist;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Remove title bar
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    //Remove notification bar
	    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.memory_angel_subscription);
        
        Intent i = getIntent();
        Bundle extras = i.getExtras();
        messageCarer = extras.getString("TAGIDEMAIL");
        mainUrl =  MemoryAngelConstant.MA_CAREER_INFO;
        
        
        
        getCareerDetails();
        
        Button quitall = (Button) findViewById(R.id.close_btn_subcription);
        quitall.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	
            	AlertDialog.Builder builder = new AlertDialog.Builder(
            			MemoryAngel_Subscription.this);
        		builder.setTitle("SUBSCRIPTION");
        		builder.setMessage("Are Sure You Want To Exit....");
        		builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        			@Override
        			public void onClick(DialogInterface arg0, int arg1) {
        				// TODO Auto-generated method stub
        				 MemoryAngel_Subscription.this.finish();
        	             finish();
        			}
        		});
        		builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        			@Override
        			public void onClick(DialogInterface arg0, int arg1) {
        				// TODO Auto-generated method stub
        			
        			}
        		});
        		builder.show();
            	
                /*Log.e("LOG", "MemoryAngel_Subscription");
                MemoryAngel_Subscription.this.finish();
                finish();*/
                // android.os.Process.killProcess(android.os.Process.myPid());
            }

        });
    }
    
    
    
    private void getCareerDetails() {
        // TODO Auto-generated method stub
        new DownloadCareerInfo().execute();
    }



    // DownloadJSON AsyncTask
        private class DownloadCareerInfo extends AsyncTask<Void, Void, Void> {

            private final String TAG = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected Void doInBackground(Void... params) {
                
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                try {
                    HttpConnectionParams.setConnectionTimeout(httpParameters,
                            timeoutConnection);
                    HttpClient httpclient = new DefaultHttpClient(httpParameters);
                    HttpPost httppost = new HttpPost(mainUrl);
                    JSONObject json = new JSONObject();
                    json.put("record1", messageCarer);
                    JSONArray postjson = new JSONArray();
                    postjson.put(json);
                    Log.e("REQUEST :", "request :" + postjson);
                    httppost.setHeader("json", json.toString());
                    httppost.getParams().setParameter("jsonpost", postjson);
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    if (is != null) {
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(is, "iso-8859-1"), 8);
                        sb = new StringBuilder();
                        sb.append(reader.readLine() + "\n");
                        String line = "0";

                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        is.close();
                        result = sb.toString();
                        Log.e("RESPONCE :", "RESPONCE :" + result);
                        if (result != null) {
                            arraylist = new ArrayList<HashMap<String, String>>();
                            jsonobject = new JSONObject(result);
                            try {
                                // Locate the array name
                                jsonarray = jsonobject.getJSONArray("posts");
                                Log.v(TAG, "Array Length Server DB :" + jsonarray.length());
                                for (int i = 0; i < jsonarray.length(); i++) {
                                    HashMap<String, String> map = new HashMap<String, String>();
                                    jsonobject = jsonarray.getJSONObject(i);
                                    CareerName = jsonobject.getString("name");
                                    CareerSMS = jsonobject.getString("carerSMS");
                                }
                            } catch (JSONException e) {
                                Log.e("Error", e.getMessage());
                                e.printStackTrace();
                            }
                        }

                    }
                }
                
                catch (Exception e) {

                }
                return null;
            }

            @Override
            protected void onPostExecute(Void args) {

            }
        }
        
        public void onClick(View view){
            
            switch(view.getId()){
                
            case R.id.notify_button :

                new SendEmail().execute();
                
                String PhoneNo1 = CareerSMS;
                //String PhoneNo1 = "0715274741";
                
                // Message Sending Method Phone Number And MEssage
                try{
                sendSMS(PhoneNo1, "Memory Angel Subscription Has Expired");
                }catch(Exception e){
                    Log.e("SMS Exeption", e.getMessage(), e);
                }
                
               callAlert();
                
                break;
                
            }
            
        }

        private void callAlert() {
			// TODO Auto-generated method stub
        	final AlertDialog alertDialog = new AlertDialog.Builder(
             		MemoryAngel_Subscription.this).create();
 			// Setting Dialog Title
 			alertDialog.setTitle("SUBSCRIPTION");
 			// Setting Dialog Message
 			alertDialog.setMessage("Memory Angel Subscription Alert Has Sent");
 			// Setting Icon to Dialog
 			alertDialog.setIcon(R.drawable.warning);
 			// Setting OK Button
 			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
 				public void onClick(DialogInterface dialog, int which) {
 					MemoryAngel_Subscription.this.finish();
    	            finish();
 					alertDialog.dismiss();
 				}
 			});
 			// Showing Alert Message
 			alertDialog.show();
 			alertDialog.setCanceledOnTouchOutside(false);
 			return;
		}



		private void sendSMS(String phoneNumber, String message) {
            String SENT = "SMS_SENT";
            String DELIVERED = "SMS_DELIVERED";

            PendingIntent sentPI = PendingIntent.getBroadcast(MemoryAngel_Subscription.this,
                    0, new Intent(SENT), 0);

            PendingIntent deliveredPI = PendingIntent.getBroadcast(
                    MemoryAngel_Subscription.this, 0, new Intent(DELIVERED), 0);

            registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        /*Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();*/
                        Log.e("SMS sent", "SMS sent");
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        /*Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();*/
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        /*Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();*/
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        /*Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();*/
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        /*Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();*/
                        break;
                    }
                }
            }, new IntentFilter(SENT));

            registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        /*Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();*/
                        break;
                    case Activity.RESULT_CANCELED:
                        /*Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();*/
                        break;
                    }
                }
            }, new IntentFilter(DELIVERED));

            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
        }

        
        private class SendEmail extends AsyncTask<Void, Void, Void> {

            @Override
            protected Void doInBackground(Void... arg0) {
                
                //String possibleEmail = sendingEmail;
                
                String possibleEmail = messageCarer;
                                
                                TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                                //String PhoneNo1 = PhoneNo;
                                

                                try {
                                    if (possibleEmail != "") {
                                        
                                        Log.e("Possible Main ",possibleEmail);

                                        GMailSender sender = new GMailSender(
                                                "devteam@mirzabros.com", "445am445pm@#");
                                        
                                        sender.sendMail(
                                                "Memory Angel Subscription Has Expired",
                                                "Dear "
                                                        + CareerName
                                                        + ","
                                                        + "\n Your Memory Angel subscription has expired. You can get back up to speed by renewing your subscription. Just click here to go to Subscription Page.\n Just pop in some valid credit card info and we'll switch everything back on. \n Kind Regards, \n Memory Angel Team",
                                                "devteam@mirzabros.com", possibleEmail);
                                        
                                        

                                        

                                    } else {
                                        Log.e("Error SendMail", "No Registered mail account");
                                    }
                                } catch (Exception e) {
                                    Log.e("SendMail", e.getMessage(), e);
                                }
                
                return null;
            }
            
        }
        

}